package com.itheima.aop;


import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {


    //把mapper层的operatelog 注入容器
    @Autowired
    private OperateLogMapper operateLogMapper;

    //把http请求注入容器
    @Autowired
    private HttpServletRequest request;

    /*
    @Before("@annotation(com.itheima.aop.Log)")
    public void before(){
        log.info("before....");
    }
    */
    @Around("@annotation(com.itheima.aop.Log)")
    public Object operateLog(ProceedingJoinPoint pjp) throws Throwable {

        //new一个POJO实体类的对象,OperateLog
        OperateLog operateLog =new OperateLog();
        //记录起始时间
        long start = System.currentTimeMillis();

        Object result = pjp.proceed();

        //用request请求获得token
        String token = request.getHeader("token");
        //解析token  用工具类 JwtUtils
        Claims claims = JwtUtils.parseJWT(token);
        //

        //operate_user
        Integer OperateUser= (Integer) claims.get("id");
        operateLog.setOperateUser(OperateUser);
        //operate_time
        operateLog.setOperateTime(LocalDateTime.now());
        //class_name
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        //methodParams  工具类Arrays可以将数组转为字符串
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));
        //methodName
        operateLog.setMethodName(pjp.getSignature().getName());
        //costName
        operateLog.setCostTime(System.currentTimeMillis()-start);
        //return_value
        operateLog.setReturnValue(result.toString());



        //写日志
        log.info("AOP记录操作日志: {}" , operateLog);
        //返回值
        return result;
    }



}
